/// 组件 * 主界面 * 页签栏

import { Divider, Dropdown, Menu, TabPane, Tabs } from 'ant-design-vue'
import { ExIcon, ExpressoPlusConfig, genComponent } from '@expresso/plus'
import type { Refresh } from '@expresso/plus'
import { pagebarCSS } from './styles'
import type { OpenRecord } from '@/stores'
import { useMenusStore } from '@/stores'
import router from '@/router'

//# 类型

type PagebarExpose = {
  refresh: () => void
}

export type { PagebarExpose }

//# 定义

/**
 * 页签栏
 */
export default genComponent({ name: 'Pagebar' }, (props, { expose }) => {
  //# 成员

  /** 路由 */
  const route = useRoute()

  /** 全局状态-菜单 */
  const menus = useMenusStore()

  /** 标签页弹框容器-引用 */
  const tabsPopupContainerRef = ref<HTMLDivElement>()
  //|
  /** 标签页右键弹框容器-引用 */
  const dropdownPopupContainerRef = ref<HTMLDivElement>()

  /** 刷新 */
  const refresh: Refresh = () => {
    menus.setRecordCachable(false)
    refresh.clearAfterEach = router.afterEach(() => {
      menus.setRecordCachable(true)
      refresh.clearAfterEach?.()
      refresh.clearAfterEach = void 0
    })
    router.push(`/redirect${route.fullPath.replace('/redirect', '')}`)
  }; {
    ExpressoPlusConfig.layouts.main.pagebar.refresh = refresh
  }

  /** 关闭 */
  const close = (key: Key) => {
    const record = menus.removeRecord(key, 'key')
    if (record) {
      if (!menus.records.list.length) {
        refresh()
      }
      else {
        router.replace(record.url)
      }
    }
  }

  //# 暴露

  expose({
    refresh,
  })

  //# 周期

  onMounted(() => {
    //
  })

  //# 渲染

  return () => (
    <div class={['pagebar', pagebarCSS]}>
      <div
        class="pagebar-tabs-popup-container"
        ref={tabsPopupContainerRef}
      />
      <div
        class="dropdown-popup-container"
        ref={dropdownPopupContainerRef}
      />
      <Tabs
        class="pagebar-tabs"
        type="editable-card"
        activeKey={menus.records.key}
        hideAdd
        tabBarGutter={0}
        get-popup-container={() => tabsPopupContainerRef.value}
        onChange={(activeKey) => {
          const url = menus.setCurrentRecord(activeKey, 'key')
          url && router.replace(useMenusStore.path2fullPath[url])
        }}
        onEdit={(targetKey, action) => {
          if (action === 'remove') {
            close(targetKey as Key)
          }
        }}
      >
        {{
          default: () => menus.records.list.map(({ key, label, closable }) => (
            <TabPane
              key={key}
              tab={(

                <Dropdown
                  trigger={['contextmenu']}
                  destroyPopupOnHide
                  getPopupContainer={() => dropdownPopupContainerRef.value!}
                >
                  {{
                    default: () => (
                      <div class="label">{label}</div>
                    ),
                    overlay: () => (
                      <Menu>
                        {
                          [
                            ['refresh', '刷新当前标签页', 'hd-icon-shuaxin1'],
                            ['close', '关闭当前标签页', 'hd-icon-guanbi1'],
                            [],
                            ['close_right', '关闭右侧标签页', 'hd-icon-youce'],
                            ['close_left', '关闭左侧标签页', 'hd-icon-zuoce'],
                            [],
                            ['close_other', '关闭其它标签页', 'hd-icon-qita'],
                            ['close_all', '关闭全部标签页', 'hd-icon-quanbu'],
                          ].map(([action, label, icon]) => {
                            if (!action) {
                              return <Divider />
                            }
                            return (
                              <Menu.Item
                                key={action}
                                icon={<ExIcon type={icon} />}
                                onClick={() => {
                                  let record: OpenRecord | undefined

                                  switch (action) {
                                    case 'refresh': {
                                      refresh()
                                      break
                                    }
                                    case 'close': {
                                      close(key)
                                      break
                                    }
                                    case 'close_right': {
                                      record = menus.filterRecordsRight(key)
                                      break
                                    }
                                    case 'close_left': {
                                      record = menus.filterRecordsLeft(key)
                                      break
                                    }
                                    case 'close_other': {
                                      record = menus.filterRecordsOther(key)
                                      break
                                    }
                                    case 'close_all': {
                                      record = menus.filterRecordsAll(key)
                                      if (!record) {
                                        refresh()
                                      }
                                      break
                                    }
                                  }

                                  if (record) {
                                    const url = menus.setCurrentRecord(record.key, 'key')
                                    url && router.replace(useMenusStore.path2fullPath[url])
                                  }
                                }}
                              >
                                {label}
                              </Menu.Item>
                            )
                          })
                        }
                      </Menu>
                    ),
                  }}
                </Dropdown>
              )}
              closable={closable}
            >
              {{
                closeIcon: () => <ExIcon type="hd-icon-close" size={14} />,
              }}
            </TabPane>
          )),
          rightExtra: () => (
            <div class="pagebar-tabs-tools">
              <div
                class="btn reload"
                title="刷新"
                onClick={refresh}
              >
                <ExIcon type="hd-icon-shuaxin" size={20} />
              </div>
            </div>
          ),
          // renderTabBar: ({ DefaultTabBar, ...props }: any) => {
          //   console.log('DefaultTabBar', props, DefaultTabBar)
          //   // return props.DefaultTabBar
          //   return (
          //     <div onContextmenu={(...params) => {
          //       console.log('contextMenu', params)
          //     }}
          //     >
          //       <DefaultTabBar {...props} />
          //     </div>
          //   )
          // },
        }}
      </Tabs>

    </div>
  )
})
